/**
 * @description:封装axios，处理拦截器
 * @author:zhangmanyi
 */


import axios from 'axios'
import { getToken } from '@/utils/auth'
import { MessageBox,Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  // baseURL: 'http://localhost:8081', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000
})

// 请求拦截
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 返回拦截
service.interceptors.response.use(
  response => {
    const res = response.data

    // 处理异常
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 401 ) {
        // token过期重新登录
        MessageBox.confirm('登录信息过期，请重新登录', '登录过期', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.response.config.url + '-' + error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
